# 公共函数库
import re
import os
import threading

from PyQt5.QtCore import QPropertyAnimation, QEasingCurve

__is_dev = True

if __is_dev:
    base_path = "./main"
else:
    base_path = "../main"

global_file_path = base_path + "/config/path.config"
global_history = base_path + "/config/history.config"


class Tool:

    def __init__(self):
        super(Tool, self).__init__()

    @staticmethod
    def set_kv(key, value, file_path=global_history):
        if Tool.str_not_empty(key) and Tool.str_not_empty(value):
            try:
                lines = [key + "=" + value + "\n"]
                config_file = open(file_path, mode="w+", encoding="utf-8")
                config_file.writelines(lines)  # 换行
                config_file.close()  # 关闭占用
            except FileNotFoundError as e:
                print(f"配置文件不存在:\t{e}")

    @staticmethod
    def get_kv(key: str, file_path=global_history):
        res = None
        if Tool.str_not_empty(key):
            try:
                file = open(file_path, mode="r", encoding="utf-8")
                lines = file.readlines()
                lens = len(lines)
                for i in range(lens):
                    line = lines[i]
                    if line.split("=")[0] == key:
                        res = Tool.get_config_value_by_key(line, key)
                file.close()
            except FileNotFoundError as e:
                print(f"配置文件不存在:\t{e}")
                pass
        return res

    @staticmethod
    def str_not_empty(_str: str):
        if _str is None:
            return False
        else:
            return not Tool.str_is_empty(_str)

    @staticmethod
    def str_is_empty(_str: str):
        if isinstance(_str, str):
            return len(_str.lstrip().rstrip()) == 0
        else:
            return False

    @staticmethod
    def re_is_path(_str: str):
        ma = re.match(r"^[A-Za-z]:/[^?*<>\"|:]+$", _str)  # 斜杠转换
        return bool(ma)

    @staticmethod
    def re_is_url(_str: str):
        ma = re.match(r"svn?://(/*)", _str)
        return bool(ma)

    # TODO： widget, start, end, _time, self, times=1
    @staticmethod
    def animate(widget, start, end, _time, self, times=1, transitionrun=None):
        if widget is not None:
            ani = QPropertyAnimation(widget, b"pos", self)
            if start is not None:
                ani.setStartValue(start)
            ani.setEndValue(end)
            ani.setDuration(_time)
            ani.setEasingCurve(QEasingCurve.InCurve)
            ani.setLoopCount(times)
            if transitionrun is not None:
                ani.valueChanged.connect(lambda v: transitionrun(v))
            ani.start()
        else:
            return None

    @staticmethod
    def save_config(conf):
        tag = False
        if len(conf) > 0:
            try:
                mode = "w+"
                key01 = "work_path"
                key02 = "svn_path"
                lines = [key01 + "=" + conf[key01] + "\n" + key02 + "=" + conf[key02]]
                config_file = open(global_file_path, mode=mode, encoding="utf-8")
                config_file.writelines(lines)  # 换行
                tag = True
                config_file.close()  # 关闭弹窗
            except Exception as e:
                print(f"配置文件不存在:\t{e}")
                pass
        else:
            print("配置为空")
        return tag

    @staticmethod
    def get_config_by_key(key):
        res = None
        if Tool.str_not_empty(key):
            try:
                file = open(global_file_path, mode="r", encoding="utf-8")
                lines = file.readlines()
                lens = len(lines)
                for i in range(lens):
                    line = lines[i]
                    if line.split("=")[0] == key:
                        res = Tool.get_config_value_by_key(line, key)
                file.close()
            except Exception as e:
                print(f"配置文件不存在:\t{e}")
        return res

    @staticmethod
    def get_config_value_by_key(_str, key):
        if Tool.str_not_empty(_str) and Tool.str_not_empty(key):
            _str = _str.strip().split("=")
            if _str[0] == key:
                return _str[1].strip()
            else:
                return None
        else:
            return None

    @staticmethod
    def set_interval(task, delay=0):
        return threading.Timer(delay, task)

    @staticmethod
    def text_line_map(_str: str, call):
        if Tool.str_is_empty(_str):
            pass
        else:
            lines = _str.splitlines()
            for line in lines:
                st = line[0:1]  # 第一个状态char
                lt = line[1:].strip()  # 文件名
                call(st, lt)
